
package com.kugou.game.sdk.ui.fragment;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity.onShowGSImageListener;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.core.VipManager;
import com.kugou.game.sdk.interfaces.OnModifyPasswordListener;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.activity.CommonSdkActivity;
import com.kugou.game.sdk.ui.activity.RechargeActivity;
import com.kugou.game.sdk.ui.widget.GameFitGridRelativeLayout;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.AsyncImageLoader;
import com.kugou.game.sdk.utils.AsyncImageLoader.ImageCallback;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 描述:充值成功界面
 *
 * @author wcj
 * @since 2015年11月2日 上午11:40:56
 */
public class RechargeSuccessFragment extends BaseSDKWorkerFragment implements onShowGSImageListener {

    private final int MSG_BACK_MODIFY_PSW = 0X0A0;

    private final int MSG_UI_MODIFY_PSW_SUCCESS = 0X0A1;

    private final int MSG_UI_MODIFY_PSW_FAILED = 0X0A2;

    private final int MSG_UI_UPDATE_COUNT_DOWN_TV = 0X0A3;

    private int second = 3;// 倒计时秒数

    private boolean isShow = true;// GS图片显示标识

    private Context mContext;

    // 修改密码栏、绑定手机号栏
    private LinearLayout mModifyPsdLayout, mBindPhoneLayout;

    // 修改密码提示信息,账号、密码、GS倒计时文本
    private TextView mModifyTipsTv, mAccountTv, mPasswordTv, mResultTv, mGSCountDown;

    // 绑定手机号按钮，修改密码按钮，进入游戏按钮
    private Button mBindBtn, mModifyBtn, mEnterGameBtn;

    // 修改密码编辑框
    private EditText mPsdEditText;

    // GS图片
    private ImageView mGSImage;

    // GS图片布局
    private GameFitGridRelativeLayout mGSLayout;

    private LinearLayout mRechargeSuccessLayout;

    private User user;

    private ScrollView mRechargeScrollView;

    public static RechargeSuccessFragment getFragment() {
        RechargeSuccessFragment fragment = new RechargeSuccessFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        user = UserManager.getInstance().getCurrentUserInternal();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews();
        sendEmptyUiMessageDelayed(MSG_UI_UPDATE_COUNT_DOWN_TV, 1000);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mContext != null && mContext instanceof RechargeActivity) {
            ((BaseCommonTitleFragmentActivity) mContext).setOnShowGSImageListener(this);
            ((BaseCommonTitleFragmentActivity) mContext).showGSIcon();
        }
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            return inflater.inflate(Rx.layout.kg_fragment_recharge_success_land, null);
        }
        return inflater.inflate(Rx.layout.kg_fragment_recharge_success, null);
    }

    int gsheight;

    private void initViews() {
        // 整个界面
        mRechargeScrollView = (ScrollView) findViewById(Rx.id.kg_recharge_success_scroll);
        mRechargeScrollView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        int y = mRechargeScrollView.getScrollY();
                        if (y >= gsheight) {
                            isShow = false;
                        } else {
                            isShow = true;
                            mGSCountDown.setVisibility(View.GONE);
                        }
                        break;
                }
                return false;
            }
        });
        mRechargeSuccessLayout = (LinearLayout) findViewById(Rx.id.kg_layout_recharge_success);
        mModifyPsdLayout = (LinearLayout) findViewById(Rx.id.kg_ll_modify_psw);
        mBindPhoneLayout = (LinearLayout) findViewById(Rx.id.kg_ll_bindphone);
        mGSLayout = (GameFitGridRelativeLayout) findViewById(Rx.id.kg_rl_gs_image);
        mPasswordTv = (TextView) findViewById(Rx.id.kg_tv_userpsw);
        mAccountTv = (TextView) findViewById(Rx.id.kg_tv_username);
        mModifyTipsTv = (TextView) findViewById(Rx.id.kg_tv_modify_psw_tips);
        mBindBtn = (Button) findViewById(Rx.id.kg_btn_continue_to_recharge);
        mModifyBtn = (Button) findViewById(Rx.id.kg_btn_modify_psw);
        mEnterGameBtn = (Button) findViewById(Rx.id.kg_btn_back_to_game);
        mPsdEditText = (EditText) findViewById(Rx.id.kg_et_modify_psw);
        mResultTv = (TextView) findViewById(Rx.id.kg_tv_result);
        mGSImage = (ImageView) findViewById(Rx.id.kg_iv_gs_image);
        mGSCountDown = (TextView) findViewById(Rx.id.kg_tv_count_second);

        mBindBtn.setOnClickListener(mListener);
        mModifyBtn.setOnClickListener(mListener);
        mEnterGameBtn.setOnClickListener(mListener);
        mGSImage.setOnClickListener(mListener);

        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            mGSLayout.setmScale(5.56f);
        } else {
            mGSLayout.setmScale(2.25f);
        }

        ViewTreeObserver contentObserver = mGSLayout.getViewTreeObserver();
        contentObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (mGSLayout == null) {
                    return;
                }

                if (Build.VERSION.SDK_INT <= 15) {
                    mGSLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    mGSLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                gsheight = mGSLayout.getHeight();
            }
        });

        mGSLayout.setVisibility(View.VISIBLE);

        String imageUrl = VipManager.getInstance().getGsImage();
        if (!TextUtils.isEmpty(imageUrl)) {
            String savePath = FolderManager.IMAGE_CACHE_FOLDER
                    + AppUtil.getFileNameFromUrl(imageUrl);
            String key = imageUrl;
            Bitmap bitmap = new AsyncImageLoader().loadImage(mContext, key, imageUrl, savePath,
                    new ImageCallback() {

                        @Override
                        public void imageLoaded(Bitmap bitmap, String key) {
                            if (bitmap != null) {
                                mGSImage.setImageBitmap(bitmap);
                            }
                        }
                    });
            if (bitmap != null) {
                mGSImage.setImageBitmap(bitmap);
            }
        }

        mResultTv.setText("恭喜主人，成功充值!");
        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user != null && user.isNeedRemindModifyPsd()) {
            mAccountTv.setText("酷狗账号：" + user.getNickName());
            mPasswordTv.setText("密        码：" + user.getPassword());
            mModifyPsdLayout.setVisibility(View.VISIBLE);
            user.setNeedRemindModifyPsd(false);
        } else if (user != null && TextUtils.isEmpty(user.getBindPhoneNum())) {
            mBindPhoneLayout.setVisibility(View.VISIBLE);
            // 发送统计-支付后显示绑定手机
            StaticsManager.sendCommonStatis(StatCmd.CMD_BI_RECHARGE_BINDPHONE_SHOW);
        } else {
            mModifyPsdLayout.setVisibility(View.GONE);
            mBindPhoneLayout.getLayoutParams().height = AppUtil.dip2px(mContext, 60);
            mBindPhoneLayout.setVisibility(View.INVISIBLE);
            mEnterGameBtn.setText("进入游戏");
        }
    }

    private View.OnClickListener mListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hideSoftInput(getActivity());
            if (v.getId() == Rx.id.kg_btn_continue_to_recharge) {
                // 发送统计-支付后点击绑定手机
                StaticsManager.sendCommonStatis(StatCmd.CMD_BI_RECHARGE_BINDPHONE_CLICKED);

                // 绑定手机
                // 如果是第三方账号，调整到补填密码
                if (TextUtils.isEmpty(user.getBindPhoneNum())) {
                    if (UserManager.getInstance().getCurrentUserInternal().isSetKugouPsd()) {
                        mContext.startActivity(CommonSdkActivity.creatIntent(mContext,
                                BindPhoneFragment.class.getName(),
                                Rx.string.kg_kugou_bind_phone_title));
                    } else {
                        startActivity(CommonSdkActivity.creatIntent(getActivity(),
                                SetLoginPsdFragment.class.getName(), Rx.string.kg_set_login_psd));
                    }
                } else {
                    mContext.startActivity(CommonSdkActivity.creatIntent(mContext,
                            UpdateBindPhoneFragment.class.getName(),
                            Rx.string.kg_kugou_bind_phone_title));
                }
            } else if (v.getId() == Rx.id.kg_btn_modify_psw) {
                // 修改密码
                String str = mPsdEditText.getText().toString().trim();
                if (TextUtils.isEmpty(str)) {
                    mModifyTipsTv.setVisibility(View.VISIBLE);
                } else {
                    Message msg = Message.obtain();
                    msg.obj = str;
                    msg.what = MSG_BACK_MODIFY_PSW;
                    sendBackgroundMessage(msg);
                }
            } else if (v.getId() == Rx.id.kg_iv_gs_image) {
                String gsQq = VipManager.getInstance().getVipInfo().getGsQQ();
                if (!TextUtils.isEmpty(gsQq)) {
                    ClipboardManager cmb = (ClipboardManager) mContext
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    cmb.setText(gsQq);
                    ToastUtil.showMsg("QQ群号已复制");
                } else {
                    ToastUtil.showMsg("复制失败");
                }
            } else {
                enterGame();
            }
        }
    };

    /**
     * 充值成功更改密码
     * 
     * @param psw
     */
    private void requestModify(String psw) {
        User user = UserManager.getInstance().getCurrentUserInternal();
        String userName = user.getNickName();
        String oldPwd = user.getPassword();
        String newPwd = psw;
        UserManager.getInstance().modifyPassword(userName, oldPwd, newPwd,
                new OnModifyPasswordListener() {
                    @Override
                    public void onSuccess() {
                        sendEmptyUiMessage(MSG_UI_MODIFY_PSW_SUCCESS);
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                        sendEmptyUiMessage(MSG_UI_MODIFY_PSW_FAILED);
                    }
                });
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_BACK_MODIFY_PSW:
                requestModify((String) msg.obj);
                break;
        }
    };

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }

        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_UI_MODIFY_PSW_FAILED:
                ToastUtil.showMsg("修改密码失败");
                break;
            case MSG_UI_MODIFY_PSW_SUCCESS:
                Intent intent = new Intent(SDKActions.ACTION_BACK_TO_GAME);
                mContext.sendBroadcast(intent);
                ToastUtil.showMsg("密码修改成功");
                break;
            case MSG_UI_UPDATE_COUNT_DOWN_TV:
                if (isShow) {
                    // 更新倒计时文本
                    mGSCountDown.setText(second + "秒");
                    second--;
                    if (second >= 0) {
                        sendEmptyUiMessageDelayed(MSG_UI_UPDATE_COUNT_DOWN_TV, 1000);
                    } else {
                        hideGS();
                        // hideGSLayout();
                    }
                }
                break;
        }
    }

    private void enterGame() {
        // 回到游戏
        Intent intent = new Intent(SDKActions.ACTION_BACK_TO_GAME);
        mContext.sendBroadcast(intent);
    }

    @Override
    public void onShow() {
        if (isShow) {
            hideGS();
        } else {
            showGS();
        }
    }

    private void hideGS() {
        mGSCountDown.setVisibility(View.GONE);// 隐藏倒计时文本
        mRechargeScrollView.smoothScrollBy(0, gsheight);
        isShow = false;
    }

    private void showGS() {
        isShow = true;
        mRechargeScrollView.smoothScrollTo(0, 0);
    }

    public void hideGSLayout() {
        isShow = false;
        int height = mGSLayout.getHeight();// GS图片布局高度
        mGSCountDown.setVisibility(View.GONE);
        ObjectAnimator hideGSLayout = ObjectAnimator.ofFloat(mRechargeSuccessLayout, "y", 0,
                -height);
        hideGSLayout.setDuration(300).start();
        hideGSLayout.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mRechargeSuccessLayout.setY((Float) animation.getAnimatedValue());
            }
        });
        hideGSLayout.addListener(new AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mGSLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });
    }

    public void showGSLayout() {
        isShow = true;
        int height = mGSLayout.getHeight();
        mGSLayout.setVisibility(View.VISIBLE);
        ObjectAnimator hideGSLayout = ObjectAnimator.ofFloat(mRechargeSuccessLayout, "y", -height,
                0);
        hideGSLayout.setDuration(300).start();
        hideGSLayout.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mRechargeSuccessLayout.setY((Float) animation.getAnimatedValue());
            }
        });
    }
}
